import { useHead } from 'unhead'

function genGoodsPageScriptHead({ $localePath, curGoodsData, priceList, curGoodsSku, commentList }) {
  const { imageUrl, name: goodsName, id: goodsId, urlName } = curGoodsData
  return {
    script: [
      {
        type: 'application/ld+json',
        innerHTML: JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'Product',
          name: goodsName,
          description: goodsName,
          url: `https://bittopup.com${$localePath(`/goods/${urlName || goodsId}`)}`,
          image: imageUrl,
          productID: curGoodsData.id,
          sku: goodsId,
          mpn: goodsId,
          aggregateRating: {
            '@type': 'AggregateRating',
            bestRating: '5',
            worstRating: '1',
            ratingCount: String(Math.max(+curGoodsData.totalRateCount, 1) * 500),
            ratingValue: String(curGoodsData.avgRate),
          },
          offers: {
            '@type': 'Offer',
            url: `https://bittopup.com/`,
            priceCurrency: 'USD',
            price: curGoodsSku.price || 0,
            priceValidUntil: '2050-11-05',
            itemCondition: 'https://schema.org/UsedCondition',
            availability: 'https://schema.org/InStock',
            seller: {
              '@type': 'Organization',
              name: 'BitTopup',
            },
          },
          review: commentList.map(({ userName, rating, comment }) => ({
            '@type': 'Review',
            reviewRating: {
              '@type': 'Rating',
              ratingValue: String(rating),
            },
            author: {
              '@type': 'Person',
              name: userName,
            },
            reviewBody: comment,
          })),
          brand: {
            '@type': 'Brand',
            name: goodsName,
          },
        }),
      },
    ],
  }
}

export function useGoodsCategorySeo(currentParentCategory, goodsList = []) {
  goodsList = goodsList.slice(0, 10)
  useHead({
    script: [
      {
        type: 'application/ld+json',
        innerHTML: JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'ItemList',
          name: currentParentCategory.categoryName,
          description: 'Explore our wide range of gift cards suitable for all occasions.',
          url: `https://bittopup.com/category/${currentParentCategory.id}/1`,
          numberOfItems: goodsList.length,
          itemListElement: goodsList.map(({ urlName, id }, idx) => ({
            '@type': 'ListItem',
            position: idx,
            url: `https://bittopup.com/goods/${urlName || id}`,
          })),
        }),
      },
    ],
  })
}

export function useGoodsSeo({ curGoodsData, curGoodsSku, commentList, curGoodsSkuList = [] }) {
  curGoodsData = unref(curGoodsData)
  const priceList = curGoodsSkuList.map(({ price }) => +price)
  const goodsName = curGoodsData.name?.replace(
    /[^\w\s\p{Script=Han}\p{Script=Hangul}\p{Script=Devanagari}\p{Script=Cyrillic}]/gu,
    '',
  )
  const { locale } = useI18n()
  const { $mt, $localePath } = useCommonPlugin()
  const isHighRisk = curGoodsData.isHighRisk
  const isDirect = isHighRisk ? false : curGoodsSku.rechargeType === 'DIRECT'
  const mustAutoGenLang = ['es', 'pt', 'fr', 'ja', 'ng'].some((langCode) => locale?.value?.includes(langCode))
  const hasSpace = !['zh'].some((langCode) => locale?.value?.includes(langCode))
  const verbWords = isDirect ? `${hasSpace ? ' ' : ''}${$mt('Top Up')}` : `${$mt('Buy')}${hasSpace ? ' ' : ''}`
  const verbWithGoodsName = isDirect ? `${goodsName}${verbWords}` : `${verbWords}${goodsName}`
  let autoTitle = isHighRisk
    ? `${verbWithGoodsName} - ${$mt('use Bitcoin, ETH, USDT, Crypto Currency')}`
    : `${verbWithGoodsName} - ${$mt('Fastest Recharge, Lowest Prices')}`
  const autoDesc = `${verbWithGoodsName}. ${$mt(
    'Fast and secure recharges await you! Enjoy instant top-ups, diverse payment choices, and 24/7 support with our reliable service.',
  )}`
  const seoTitle = mustAutoGenLang ? autoTitle : curGoodsData.seoTitle || autoTitle
  const seoDescription = mustAutoGenLang ? autoDesc : curGoodsData.seoDescription || autoDesc
  useHead({
    ...genGoodsPageScriptHead({ $localePath, curGoodsData, priceList, curGoodsSku, commentList }),
  })
  const keywords1 = `${hasSpace ? `${verbWords} ` : verbWords}$goodsName$`.replace(hasSpace ? '' : /\s/g, '')
  const keywords2 = `$goodsName$ ${$mt('Official')} ${$mt('Online')} ${verbWords}`.replace(hasSpace ? '' : /\s/g, '')
  const keywords3 = `$goodsName$ ${verbWords}`.replace(hasSpace ? '' : /\s/g, '')
  const keywords4 = `${$mt('How to')} ${keywords1}`.replace(hasSpace ? '' : /\s/g, '')
  useSeoMeta({
    title: seoTitle,
    ogTitle: seoTitle,
    keywords() {
      return [keywords1, keywords2, keywords3, keywords4].join(',').replace(/\$goodsName\$/g, goodsName)
    },
    description: seoDescription,
    ogDescription: seoDescription,
    ogImage: curGoodsData.imageUrl,
    twitterCard: 'summary_large_image',
  })
}

export function useGoodsReviewSeo({ curGoodsData }) {
  curGoodsData = unref(curGoodsData)
  const goodsName = curGoodsData.name
  const { $mt } = useCommonPlugin()
  const seoTitle = `${goodsName} ${$mt('Reviews: Real Customer Opinions and Ratings ')} | BitTopup`
  const seoDescription = `${$mt('Read genuine customer reviews at BitTopup for')} ${goodsName}. ${$mt(
    'Discover what buyers say about the quality, performance, and value of',
  )} ${goodsName}. ${$mt('Your feedback matters – join our community and share your experience with')} ${goodsName}!`
  useSeoMeta({
    title: seoTitle,
    ogTitle: seoTitle,
    description: seoDescription,
    ogDescription: seoDescription,
    ogImage: curGoodsData.imageUrl,
    twitterCard: 'summary_large_image',
  })
}

export function useArticleSeo(articleData) {
  const { $mt } = useCommonPlugin()
  return useSeoMeta({
    title: articleData.title?.slice(0, 50) + ` - BitTopup`,
    ogTitle: articleData.title?.slice(0, 50) + ` - BitTopup`,
    description: articleData.title?.slice(0, 64),
    ogDescription: articleData.title?.slice(0, 64),
    ogImage: articleData.imageUrl,
    twitterCard: 'summary_large_image',
  })
}

export function useGameSeo(introduceDetail) {
  const { $mt } = useCommonPlugin()
  const title = introduceDetail.title + ` ${$mt('Top-Up: Instant Recharge for Exclusive Gifts & More!')} - BitTopup`
  const desc = `${introduceDetail.title} ${$mt('Quick and secure top-up services! Recharge now to unlock exclusive gifts, premium features, and more. Enjoy seamless transactions with instant delivery.')}`
  return useSeoMeta({
    title,
    ogTitle: title,
    description: desc,
    ogDescription: desc,
    ogImage: introduceDetail.imageUrl,
    twitterCard: 'summary_large_image',
  })
}

export function useIndexSeo() {
  useHead({
    script: [
      {
        type: 'application/ld+json',
        innerHTML: JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'WebSite',
          name: 'BitTopup',
          url: 'https://bittopup.com',
          description:
            'This is a professional online platform for gift card sales, offering a wide variety of gift cards for different brands and purposes.',
        }),
      },
    ],
  })
}

export function useGlobalRichSeo() {
  useHead({
    script: [
      {
        type: 'application/ld+json',
        innerHTML: JSON.stringify({
          '@context': 'https://schema.org',
          '@type': 'Organization',
          name: 'BitTopup',
          legalName: 'BitTopup',
          url: 'https://bittopup.com/',
          logo: 'https://bittopup.com/logo.png',
          founders: [
            {
              '@type': 'Person',
              name: 'Vijay Adam',
            },
          ],
          potentialAction: {
            '@type': 'SearchAction',
            target: 'https://bittopup.com/common/search?keywords={search_term_string}',
            'query-input': 'required name=search_term_string',
          },
          address: {
            '@type': 'PostalAddress',
            streetAddress: '291 Brighton Road',
            addressLocality: 'South Croydon',
            addressRegion: 'Croydon',
            postalCode: 'CR2 6EQ',
            addressCountry: 'United Kingdom',
          },
          contactPoint: {
            '@type': 'ContactPoint',
            contactType: 'customer support',
            telephone: '+46-633723580',
            email: 'service@bittopup.com',
          },
        }),
      },
    ],
  })
}
